<template>
  <view class="play-box">
    <!-- 播放针 -->
    <view :class="['needle', play && !end ? 'play' : '']">
      <image src="~@/static/img/needle.png"
             @click="play = !play"></image>
    </view>

    <!-- 播放器主体 -->
    <view class="detail-play"
          @click="play = !play">
      <view class="play-img">
        <image :src="detailData.picUrl"
               :class="{'playing': play && !end}">
        </image>
        <view :class="['iconfont', play && !end ? 'iconpause': 'iconbofang1']"></view>
      </view>
    </view>

    <!-- 歌词区域 -->
    <view class="music-lyrics-box">
      <view class="lyric-scroll-box"
            :style="{transform: `translateY(${ - (lyricIndex - 1) * 80 }rpx)`}">
        <view v-for="(item, index) in lyric"
              :key="index"
              :class="{'lyric':true ,'now': index === lyricIndex}">
          {{item.lyric}}
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import { mapActions } from 'vuex'

  export default {
    name: "audio-play",
    model: {
      prop: 'value',
      event: 'input'
    },
    props: {
      // 是否播放
      value: {
        type: Boolean,
        default: false
      },
      // 歌曲信息
      detailData: {
        type: Object,
        default: () => ({})
      },
      // 歌词数据
      lyric: {
        type: Array,
        default: () => []
      },
      // 歌曲数据
      playData: {
        type: Object,
        default: () => ({})
      }
    },
    computed: {
      // 控制播放组件是否播放，暂停
      play: {
        get() {
          return this.value
        },
        set(v) {
          // 如果play为true则播放，false则暂停
          if (this.playVideo) {
            v ? this.playVideo.play() : this.playVideo.pause()
          } else {
            uni.$showError('该歌曲暂无版权')
          }
          this.$emit('input', v)
        }
      }
    },
    data() {
      return {
        // 当前播放进度下对应的歌词index
        lyricIndex: 0,
        // 是否播放结束(音乐加载成功前默认为true)
        end: true,
        // 播放组件
        playVideo: null
      }
    },
    beforeDestroy() {
      if(!this.playVideo) return
      
      // #ifdef H5
      this.playVideo.destroy()
      // #endif

      // #ifdef MP || APP
      this.playVideo.stop()
      console.log(1);
      // #endif
    },
    watch: {
      playData() {
        this.initPlayVideo()
      }
    },
    methods: {
      ...mapActions('play-video', ['getNextMusicId']),

      // 播放组件
      initPlayVideo() {
        if (!this.playData.url)
          return uni.$showError('该歌曲暂无版权')
        // 获取音频播放器
        let playVideo = null
        // WX、APP 使用背景音乐播放器
        // #ifdef MP || APP
        playVideo = uni.getBackgroundAudioManager()
        // #endif

        // H5端使用普通音乐播放器
        // #ifdef H5
        playVideo = uni.createInnerAudioContext()
        // #endif

        if (playVideo) {
          playVideo.title = this.detailData.name || ''
          playVideo.src = this.playData.url

          // 音乐加载完成后判断播放状态 如果当前状态为播放，则播放音乐
          playVideo.onCanplay(() => {
            console.log('onCanplay');
            // 音乐加载成功，设置为false
            this.end = false
            this.play ? this.playVideo.play() : this.playVideo.pause()
          })
          // 音乐进度更新时调用，判断歌词是否需要切换
          playVideo.onTimeUpdate(this.changeLyricIndex)
          // 音乐播放自然结束
          playVideo.onEnded(() => {
            // 结束后歌词index设置最后一个（因为歌词最后一次时间转换后可能和结束时间对不上）
            this.lyricIndex = this.lyric.length - 1
            this.end = true
            this.play = false

            // 播放下一首
            this.playNext()
          })
        }

        this.playVideo = playVideo
      },

      // 判断歌词位置
      changeLyricIndex() {
        if (!this.lyric || !this.lyric.length) return
        for (let i = this.lyricIndex; i < this.lyric.length - 1; i++) {
          // 找到对应时间的歌词索引
          if (this.lyric[i].time < this.playVideo.currentTime &&
            this.lyric[i + 1].time > this.playVideo.currentTime) {
            this.lyricIndex = i
            break
          }
        }
      },

      // 播放下一首
      async playNext() {
        let nextId = await this.getNextMusicId()
        if (nextId == null)
          return uni.$showError('没有下一首了')

        uni.redirectTo({
          url: `/pages/pageDetail/pageDetail?id=${nextId}`,
        })
      }
    }
  }
</script>

<style lang="scss"
       scoped>
  .play-box {
    .needle {
      height: 186rpx;
      position: relative;
      z-index: 10000;
      transform: rotate(-15deg);
      transition: 1s all;
      transform-origin: center 0;

      &.play {
        transform: rotate(0);
      }

      image {
        margin: 0 auto;
        padding-left: 130rpx;
        width: 220rpx;
        height: 350rpx;
      }
    }

    .detail-play {
      position: relative;
      width: 580rpx;
      height: 580rpx;
      background-image: url(~@/static/img/disc.png);
      background-size: cover;
      margin: 0 auto;


      .play-img {
        position: absolute;
        width: 355rpx;
        height: 355rpx;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);

        @keyframes rotate {
          from {
            transform: rotate(0deg);
          }

          to {
            transform: rotate(360deg);
          }
        }

        .playing {
          animation-play-state: running;
        }

        image {
          animation: 10s linear rotate infinite;
          animation-play-state: paused;
          width: 100%;
          height: 100%;
          border-radius: 50%;
          transform-origin: center;
        }

        .iconfont {
          position: absolute;
          color: #FFFFFF;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          font-size: 80rpx;
          font-weight: 900;
        }
      }
    }

    .music-lyrics-box {
      margin-top: 40rpx;
      height: 240rpx;
      overflow: hidden;
      text-align: center;

      .lyric-scroll-box {
        transition: .3s all;

        .lyric {
          width: 500rpx;
          height: 80rpx;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          margin: 0 auto;
          font-size: 28rpx;
          line-height: 80rpx;
          color: #333;

          &.now {
            font-size: 30rpx;
            color: #FFFFFF;
          }
        }
      }

    }
  }
</style>
